package netWork;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86186
 * Date: 2023-10-13
 * Time: 16:58
 */
public class UdpEchoServer {
    //创建一个socket对象，后面网卡操作的基础
    DatagramSocket socket = null;

    public UdpEchoServer(int port) throws SocketException {
        //当服务器端创建socket的时候指定端口
        this.socket = new DatagramSocket(port);
    }

    public void run() throws IOException {
        System.out.println("服务端启动");
        //这里为什么要用while(true)循环，因为我们不知道什么时候客户端会发送来请求，所以服务端就需要无时无刻不在工作
        while (true) {
            //创建一个数据报对象用来接收服务器端发送来的数据
            DatagramPacket requestSocket = new DatagramPacket(new byte[4096], 4096);
            //接收数据，并且将接收的数据输出到requestSocket中
            socket.receive(requestSocket);

            //将接收到的二进制数据转换为字符串
            String request = new String(requestSocket.getData(), 0 ,requestSocket.getLength(),"UTF-8");

            //服务端做出业务处理
            String response = process(request);

            //将服务端做出的业务字符串打包成数据报，这里需要指定目的IP和目的端口号
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes("UTF-8"), response.getBytes().length,
                    requestSocket.getSocketAddress());

            socket.send(responsePacket);

            System.out.printf("[%s:%d] req=%s res=%s\n",requestSocket.getSocketAddress(), requestSocket.getPort(),
                    request,response);
        }
    }

    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer udpEchoServer = new UdpEchoServer(9906);
        udpEchoServer.run();
    }

}
